package com.ys.everydaynews.view

import android.content.Context
import android.content.res.TypedArray
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import com.ys.everydaynews.R
import com.ys.everydaynews.databinding.ItemUserInfoViewBinding
import com.ys.everydaynews.utils.ImageLoaderUtil

class UserInfoItemView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : FrameLayout(context, attrs) {

    private var leftTitle: String? = ""
    private var isShowImage: Boolean = false
    private val userType: TypedArray =
        context.obtainStyledAttributes(attrs, R.styleable.UserInfoItem)
    private var mUserOnClickListener: UserOnClickListener? = null
    private var tvRight: TextView? = null
    private var imgHead: ImageView? = null

    init {
        leftTitle = userType.getString(R.styleable.UserInfoItem_leftTitleTxt)
        isShowImage = userType.getBoolean(R.styleable.UserInfoItem_isShowImage, false)
        userType.recycle()
        initView()
    }

    private fun initView() {
        val view = LayoutInflater.from(context).inflate(R.layout.item_user_info_view, this)
        val tvLeft: TextView = view.findViewById(R.id.tv_left)
        imgHead = view.findViewById(R.id.img_head)
        tvRight = view.findViewById(R.id.tv_right)
        val rlItem: RelativeLayout = view.findViewById(R.id.rl_item)
        tvLeft.text = leftTitle
        rlItem.setOnClickListener { mUserOnClickListener!!.userOnClick(it) }
        ifShow()
    }

    private fun ifShow() {
        if (isShowImage) {
            imgHead!!.visibility = View.VISIBLE
        } else {
            imgHead!!.visibility = View.GONE
        }
    }

    fun setImageUrl(url: String) {
        ImageLoaderUtil.loadCircleImage(context, url, imgHead!!)
    }

    fun setTextRight(txt: String) {
        tvRight!!.text = txt
    }

    fun setTxtRightColor(colorId: Int) {
        tvRight!!.setTextColor(ContextCompat.getColor(context, colorId))
    }

    fun setUserOnClickListener(mUserOnClickListener: UserOnClickListener) {
        this.mUserOnClickListener = mUserOnClickListener
    }

    interface UserOnClickListener {
        fun userOnClick(view: View)
    }
}